package org.easier.framework.elasticsearch.hightlevel.impl;

import lombok.Data;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.util.Optional;

@Data
public class EsClientFactory {

    private RestHighLevelClient restHighLevelClient;

    public EsClientFactory(EsConfig configuration) {
        init(configuration);
    }

    protected void init(EsConfig configuration) {
        RestClientBuilder builder = RestClient.builder(configuration.getHttpHosts());

        //密码设置
        if (configuration.getUserName() != null && configuration.getPassword() != null) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(configuration.getUserName(), configuration.getPassword()));
            builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        }


        //请求链接超时时间配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(getNotNullValue(configuration.getConnectTimeOut(), -1));
            requestConfigBuilder.setSocketTimeout(getNotNullValue(configuration.getSocketTimeOut(), -1));
            requestConfigBuilder.setConnectionRequestTimeout(getNotNullValue(configuration.getConnectionRequestTimeOut(), -1));
            return requestConfigBuilder;
        });

        restHighLevelClient = new RestHighLevelClient(builder);
    }


    public RestHighLevelClient getRestHighLevelClient() {
        return restHighLevelClient;
    }

    private int getNotNullValue(Integer val, int defaultVal) {
        return Optional.ofNullable(val).orElse(defaultVal);
    }
}
